package top.dimples.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.dimples.common.ApiResponse;
import top.dimples.common.Status;
import top.dimples.model.Image;
import top.dimples.service.ImageService;
import top.dimples.service.UploadService;
import top.dimples.vo.image.ImageUploadVO;

import java.io.File;
import java.io.IOException;

/**
 * @author Dimples_YJ
 * @date 2021/12/9
 */
@Slf4j
@Service
public class UploadServiceImpl implements UploadService {

    @Value("${spring.servlet.multipart.location}")
    private String fileTempPath;

    @Autowired
    private ImageService imageService;

    @Override
    public ApiResponse localUpload(MultipartFile file,String type) {
        if (file.isEmpty()) {
            return ApiResponse.of(Status.BAD_REQUEST.getCode(),"文件不能为空!",null);
        }
        String fileName = file.getOriginalFilename();
        String rawFileName = StrUtil.subBefore(fileName, ".", true);
        String fileType = StrUtil.subAfter(fileName, ".", true);
        String fileUrlName = rawFileName + "-" + DateUtil.current() + "." + fileType;
        String localFilePath = StrUtil.appendIfMissing(fileTempPath, "/") + fileUrlName;
        try {
            file.transferTo(new File(localFilePath));
        } catch (IOException e) {
            log.error("【文件上传至本地】失败，绝对路径：{}", localFilePath);
            return ApiResponse.of(Status.ERROR.getCode(),"文件删除失败！",null);
        }
        // 设置默认图片类型
        if(StrUtil.isEmpty(type)){
            type = "普通图片";
        }

        log.info("【文件上传至本地】绝对路径：{}", localFilePath);

        Image image = Image.builder()
                .localUrl(localFilePath)
                .url(fileUrlName)
                .type(type)
                .build();
        imageService.save(image);

        ImageUploadVO imageUploadVO = new ImageUploadVO();
        BeanUtils.copyProperties(image,imageUploadVO);

        return ApiResponse.of(Status.SUCCESS.getCode(), "上传成功",imageUploadVO);
    }
}
